package ua.pp.fland.rest.simple.client;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.client.RestOperations;
import ua.com.stormlabs.tiny.licenseserver.beans.User;

import java.net.SocketException;

/**
 * @author mbondarenko
 * @version 1.0 12/24/12
 */
class TinyLicenseServerClient {

    private final RestOperations restTemplate;

    public TinyLicenseServerClient(RestOperations restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String getResponse(String login, String password, String mac, String opaque, String url) throws SocketException {
        String key = buildKey(login, password, mac, opaque);
        return restTemplate.getForObject(url + "/service/validate?userName=" + login +
                "&key=" + key + "&opaque=" + opaque + "&mac=" + mac, String.class);
    }

    public User getUserDetails(String login, String password, String mac, String opaque, String url) {
        String key = buildKey(login, password, mac, opaque);
        return restTemplate.getForObject(url + "/service/getUserInfo?userName=" + login +
                "&key=" + key + "&opaque=" + opaque + "&mac=" + mac, User.class);
    }

    private String buildKey(String login, String password, String mac, String opaque) {
        return DigestUtils.md5Hex("userName=" + login + "licenseCode=" + password
                + "mac=" + mac + "opaque=" + opaque);
    }
}
